<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label-width="400" label="项目名/订单号" prop="genProjectName">
        <el-input
          v-model="queryParams.genProjectName"
          placeholder="请输入代码生成项目名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="库名称" prop="genBaseName">
        <el-input
          v-model="queryParams.genBaseName"
          placeholder="请输入生成数据库名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['generator:records:test']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['generator:records:test']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['generator:records:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['generator:records:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recordsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="主键" width="55" align="center" prop="id"/>
      <el-table-column label="项目名" width="155" align="center" prop="genProjectName"/>
      <el-table-column label="库名称" width="155" align="center" prop="genBaseName"/>
      <el-table-column label="sql表语句" :show-overflow-tooltip="true" width="155" align="center" prop="genBaseSql"/>
      <el-table-column label="类型" width="155" align="center" prop="genType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.biz_gen_type" :value="scope.row.genType"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="155" align="center" prop="genStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.biz_gen_status" :value="scope.row.genStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="状态说明" width="155" align="center" prop="genStatusInfo"/>
      <el-table-column label="审核人" width="155" align="center" prop="genReviewer"/>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" width="420" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!--          <el-button-->
          <!--            size="small"-->
          <!--            type="primary"-->
          <!--            icon="el-icon-edit"-->
          <!--            v-hasPermi="['generator:records:edit']"-->
          <!--          >查看详情-->
          <!--          </el-button>-->

          <el-button
            size="small"
            type="primary"
            @click="handleCheck(scope.row)"
          >更多
          </el-button>

          <!--          <el-button-->
          <!--            size="small"-->
          <!--            type="primary"-->
          <!--            v-if="scope.row.genStatus=='2'"-->
          <!--            @click="handleExamine(scope.row)"-->
          <!--            v-hasPermi="['generator:records:toExamine']"-->
          <!--          >提交审核-->
          <!--          </el-button>-->
          <!--          <el-button-->
          <!--            size="small"-->
          <!--            type="primary"-->
          <!--            v-if="scope.row.genStatus=='3'"-->
          <!--            @click="handleExamineSuccess(scope.row)"-->
          <!--            v-hasPermi="['generator:records:examineSuccess']"-->
          <!--          >审核通过-->
          <!--          </el-button>-->
          <!--          <el-button-->
          <!--            size="small"-->
          <!--            type="warning"-->
          <!--            v-if="scope.row.genStatus=='3'"-->
          <!--            @click="handleReject(scope.row)"-->
          <!--            v-hasPermi="['generator:records:toReject']"-->
          <!--          >驳回申请-->
          <!--          </el-button>-->
          <el-button
            size="small"
            type="primary"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-if="scope.row.genStatus=='0'||scope.row.genStatus=='5'||scope.row.genStatus=='6'"
            v-hasPermi="['generator:records:toExamine']"
          >修改
          </el-button>
          <el-button
            size="small"
            type="danger"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['generator:records:remove']"
            v-if="scope.row.genStatus=='0'||scope.row.genStatus=='5'||scope.row.genStatus=='6'"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改代码生产记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="990px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目名" prop="genProjectName">
              <el-input v-model="form.genProjectName" placeholder="请输入代码生成项目名"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="sql语句" prop="genBaseSql">
              <el-input v-model="form.genBaseSql" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="代码类型" prop="genType">
              <el-select v-model="form.genType" placeholder="请选择下拉选择" clearable :style="{width: '100%'}">
                <el-option
                  v-for="dict in dict.type.biz_gen_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="form.genStatus=='0'||form.genStatus ==null||form.genStatus ==''"
                   @click="submitDraft">保存草稿
        </el-button>
        <el-button type="success" @click="submitForm">提交测试</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="check" width="990px" append-to-body>
      <el-descriptions class="margin-top" title="代码生成详情" :column="2" border>
        <template slot="extra">
          <el-button
            size="small"
            type="primary"
            v-if="checkFrom.genStatus=='2'"
            @click="handleExamine(checkFrom)"
            v-hasPermi="['generator:records:toExamine']"
          >提交审核
          </el-button>
          <el-button
            size="small"
            type="primary"
            v-if="checkFrom.genStatus=='3'"
            @click="handleExamineSuccess(checkFrom)"
            v-hasPermi="['generator:records:examineSuccess']"
          >审核通过
          </el-button>
          <el-button
            size="small"
            type="warning"
            v-if="checkFrom.genStatus=='3'"
            @click="handleReject(checkFrom)"
            v-hasPermi="['generator:records:toReject']"
          >驳回申请
          </el-button>
        </template>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-user"></i> 用户名
          </template>
          {{ checkFrom.username }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-mobile"></i> 项目名称
          </template>
          {{ checkFrom.genProjectName }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-data-board"></i> 数据库名称
          </template>
          {{ checkFrom.genBaseName }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-document-copy"></i> 生成类型
          </template>
          <dict-tag :options="dict.type.biz_gen_type" :value="checkFrom.genType"/>
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-success"></i> 审核状态
          </template>
          <dict-tag :options="dict.type.biz_gen_status" :value="checkFrom.genStatus"/>
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-info"></i> 状态说明
          </template>
          {{ checkFrom.genStatusInfo }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-user-solid"></i> 审核人
          </template>
          {{ checkFrom.genReviewer }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-user"></i> 创建人
          </template>
          {{ checkFrom.createBy }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-time"></i> 创建时间
          </template>
          {{ checkFrom.createTime }}
        </el-descriptions-item>
      </el-descriptions>
      <el-descriptions class="margin-top" :column="2" border>
        <el-descriptions-item label="SQL语句">
          {{ checkFrom.genBaseSql }}
        </el-descriptions-item>
      </el-descriptions>

      <el-row :gutter="10" style="margin: 20px">
        <el-col :span="1.5">
          <el-button
            size="small"
            type="success"
            v-if="checkFrom.genStatus=='4'"
            :disabled="multipleTable"
            @click="handleGenCode(checkFrom)"
          >生产代码
          </el-button>
        </el-col>
      </el-row>

      <el-table
        :data="checkTableList"
        style="width: 100%" @selection-change="handleTablesChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column
          prop="engine"
          label="存储引擎"
          width="170">
        </el-table-column>
        <el-table-column
          prop="tableName"
          label="表名称"
          width="240">
        </el-table-column>
        <el-table-column
          prop="tableComment"
          label="注释"
          width="240">
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          width="230">
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {
  listRecords,
  getRecords,
  delRecords,
  addRecords,
  updateRecords,
  saveDraft,
  toExamine,
  toReject,
  examineSuccess,
  postGenCode,
  getCheck
} from "@/api/generator/records";

export default {
  name: "Records",
  dicts: ['biz_gen_type', 'biz_gen_status'],

  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      multipleTable:true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 代码生产记录表格数据
      recordsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      check: false,
      checkFrom: {
        genStatus:null
      },
      checkTableList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        mainBaseId: null,
        testBaseId: null,
        genProjectName: null,
        genBaseName: null,
        genBaseSql: null,
        genType: null,
        genStatus: null,
        genStatusInfo: null,
        genReviewer: null,
      },
      // 表单参数
      form: {},
      //生成代码表选中数组
      tables:[],
      // 表单校验
      rules: {
        genProjectName: [
          {required: true, message: "代码生成项目名不能为空", trigger: "blur"}
        ],
        genBaseName: [
          {required: true, message: "生成数据库名称不能为空", trigger: "blur"}
        ],
        genBaseSql: [
          {required: true, message: "生成sql表语句不能为空", trigger: "blur"}
        ],
        genType: [
          {required: true, message: "生成类型不能为空", trigger: "change"}
        ],
        genStatus: [
          {
            required: true,
            message: "审核状态 0:草稿 1:已提交 2:已测试 3:待审核 4:已审核 5:已驳回 6:测试未通过不能为空",
            trigger: "change"
          }
        ],
        genStatusInfo: [
          {required: true, message: "状态说明不能为空", trigger: "blur"}
        ],
        genReviewer: [
          {required: true, message: "审核人不能为空", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询代码生产记录列表 */
    getList() {
      this.loading = true;
      listRecords(this.queryParams).then(response => {
        this.recordsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        mainBaseId: null,
        testBaseId: null,
        genProjectName: null,
        genBaseName: null,
        genBaseSql: null,
        genType: null,
        genStatus: null,
        genStatusInfo: null,
        genReviewer: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 数据表生成代码多选框选中数据
    handleTablesChange(selection) {
      this.tables = selection.map(item => item.tableName)
      this.multipleTable = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加代码生产记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$modal.loading("正在加载，请稍后...");
      this.reset();
      const id = row.id || this.ids
      getRecords(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改代码生产记录";
      });
      this.$modal.closeLoading();
    },
    /** 查看详情 */
    async handleCheck(row) {
      this.$modal.loading("正在加载，请稍后...");
      this.checkFrom = {};
      this.checkTableList = [];
      const id = row.id
      await getCheck(id).then(response => {
        console.log("check", response)
        this.checkFrom = response.data
        if (this.checkFrom.genStatus == '2' || this.checkFrom.genStatus == '3' || this.checkFrom.genStatus == '4' || this.checkFrom.genStatus == '5') {
          this.checkTableList = response.tableList;
        }
        this.$modal.closeLoading();
      });
      this.check = true;
    },
    /**提交审核*/
    handleExamine(row) {
      this.$modal.confirm('确定提交审核？').then(function () {
        return toExamine(row.id);
      }).then(() => {
        this.$modal.msgSuccess("提交成功！等待审核");
        this.check = false;
        this.getList();
      })
    },
    /**审核通过*/
    handleExamineSuccess(row) {
      this.$modal.confirm('确定审核通过？').then(function () {
        return examineSuccess(row.id);
      }).then(() => {
        this.$modal.msgSuccess("已审核通过");
        this.check = false;
        this.getList();
      })
    },
    handleGenCode(row) {
      console.log(this.tables)
      console.log(row.id)
      this.$modal.loading("正在加载，请稍后...");
      this.$prompt('请填写代码模块名称！', '必填', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[A-Za-z]+$/, // 正则表达式，只允许英文字母
        inputErrorMessage: '输入不能为空且只能包含英文字母' // 当校验失败时显示的错误消息
      }).then(({ value }) => {
        let data = {
          "tables": this.tables,
          "id": row.id,
          "model": value
        };
        this.$download.zipPost("/generator/records/code" ,data, "code.zip");
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '输入取消'
        });
      });
      this.$modal.closeLoading();
    },
    /**驳回申请*/
    handleReject(row) {
      this.$prompt('确定驳回吗？请输入驳回原因！', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({value}) => {
        console.log(value)
        toReject(row.id, value).then(response => {
          if (response.data == 1) {
            this.$modal.msgSuccess("已驳回！");
          }
          this.check = false;
          this.getList();
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消驳回'
        });
      });
    },
    submitDraft() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.$modal.loading("正在测试，请稍后...");
          saveDraft(this.form).then(response => {
            this.$modal.msgSuccess("保存成功");
            this.open = false;
            this.getList();
          });
          this.$modal.closeLoading();
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.$modal.loading("正在测试，请稍后...");
          if (this.form.id != null) {
            updateRecords(this.form).then(response => {
              this.$modal.msgSuccess("提交成功！");
              this.open = false;
              this.getList();
            });
          } else {
            addRecords(this.form).then(response => {
              this.$modal.msgSuccess("提交成功！");
              this.open = false;
              this.getList();
            });
          }
          this.$modal.closeLoading();
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.loading("正在测试，请稍后...");
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除代码生产记录编号为"' + ids + '"的数据项？').then(function () {
        return delRecords(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
      this.$modal.closeLoading();
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('generator/records/export', {
        ...this.queryParams
      }, `records_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
